package chaoyue.study.pool;

import chaoyue.study.ThreadUtils;

import java.util.concurrent.*;

/**
 * CompletionService
 * 可以按照完成时间的先后返回任务结果，先执行完先返回
 * submit：提交任务，可以处理Runnable和Callable
 * take：阻塞获取任务执行结果
 * poll：非阻塞获取任务执行结果
 * CompletionService的使用依赖线程池，通过ExecutorCompletionServices来使用
 */
public class CompletionServiceTest {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService<>(pool);
        // 提交任务
        for (int i = 5; i >= 1; i--) {
            completionService.submit(new Task(i));
        }
        // 获取任务执行结果
        for (int i = 0; i < 5; i++) {
            Future<Integer> future = completionService.take();
            System.out.println("返回顺序：" + future.get());
        }
        pool.shutdown();
    }

    private static class Task implements Callable<Integer> {
        // 任务执行时间
        private int timeout;

        public Task(int timeout) {
            this.timeout = timeout;
        }

        @Override
        public Integer call() throws Exception {
            System.out.println("执行顺序：" + timeout);
            ThreadUtils.sleep(timeout);
            return timeout;
        }
    }
}
